package com.ruoyi.framework.sharding;

import org.springframework.context.annotation.Configuration;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @Description: shardingSphere分表配置
 */
@Configuration
public class ShardingConfig {

    /** 配置文件路径 */
    private static final String CONFIG_FILE = "sharding.yaml";
    /**
     * 配置文件输出目录（与 JAR 包同级）
     */
    private static final String OUTPUT_DIR = new File(System.getProperty("user.dir")).getAbsolutePath();

    /**
     * 配置文件输出路径
     */
    private static final String OUTPUT_FILE_PATH = OUTPUT_DIR + File.separator + CONFIG_FILE;


    /**
     * 获取数据源配置
     */
    public static File getShardingYAMLFile() {
        try (InputStream inputStream = ShardingConfig.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) {
            if (inputStream == null) {
                throw new IllegalArgumentException("Resource " + CONFIG_FILE + " not found in JAR.");
            }

            // 创建输出文件
            Files.createDirectories(Paths.get(OUTPUT_DIR)); // 确保输出目录存在
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH))) {
                // 读取输入流并写入文件
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    writer.write(line);
                    writer.newLine();
                }
            }

            System.out.println("Extracted " + CONFIG_FILE + " to " + OUTPUT_FILE_PATH);
            return  new File(OUTPUT_FILE_PATH);
        } catch ( IOException e) {
            e.printStackTrace();
        }
        return null;
//        System.out.println(ShardingConfig.class.getClassLoader().getResource(CONFIG_FILE));
//        return new File(Objects.requireNonNull(
//                ShardingConfig.class.getClassLoader().getResource(CONFIG_FILE), String.format("File `%s` is not existed.", CONFIG_FILE)).getFile());
    }
}
